(function(){
  var keys = document.querySelectorAll('div.key')
  //给key添加鼠标点击事件监听
  keys.forEach(function (key){
    key.addEventListener('click', handleClick);
    //过渡完成后移除css
    key.addEventListener('transitionend', removeClassPlay)
  })
  //给键盘添加事件监听
  document.addEventListener('keydown',handleKeyPress)
  function handleKeyPress(e){
    var code = e.keyCode;
    //console.log(code);
    playSound(code);
  }
  function handleClick(e){
    var code;
    //console.log(e.target);
    if (this == e.target) {
      code = this.getAttribute('data-key')
    } else {
      code = e.target.parentElement.getAttribute("data-key");
    }
    playSound(code);
  }
  function playSound(code){
    var audioFile = document.querySelector('audio[data-key="'+ code +'"]'),
        elem;
    if(!audioFile) return
    elem = document.querySelector('div[data-key="'+ code +'"]')
    //console.log(audioFile);
    //每次调用清零
    //elem.className = 'key'
    audioFile.currentTime = 0;
    audioFile.play();
    //改变css
    //elem.classList += ' playing'
    elem.classList.add('playing')
  }
  function removeClassPlay(e){
    console.log('22');
    //this.className = 'key';
    e.target.classList.remove('playing')
  }
})()